/*
 * SocketConnection.java   0.0.1    28/set/2009
 * 
 * Copyright (c) 2009 mentalsmash.org
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * The use of the Apache License does not indicate that this project is
 * affiliated with the Apache Software Foundation.
 */
package org.mentalsmash.tazio.net.cs.client;

import java.io.IOException;
import java.io.Serializable;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.mentalsmash.tazio.net.cs.MessageInputStream;
import org.mentalsmash.tazio.net.cs.MessageOutputStream;
import org.mentalsmash.tazio.net.cs.RuntimeCSSubsystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Implementation of {@link Connection} using Internet sockets to communicate
 * with the server.
 * <p>
 * This implementations uses an {@link ExecutorService} instance passed to it at
 * construction time, to send a request to the server and receive a response.
 * Therefore - depending of the kind of <tt>Executor</tt> passed at construction
 * time - there may be a single thread sending each message through this
 * connection (and possibly other connections), or at the opposite extreme, a
 * thread may be created on a per-request basis.
 * </p>
 * <p>
 * <strong>Therefore</strong>, do not make any assumptions on how the requests
 * are executed, except that they are not made by the calling thread
 * </p>
 * 
 * @author Andrea Reale <andrea.reale@gmail.com>
 * @version 0.0.1
 */
public class SocketConnection implements Connection {

    private final static Logger log = LoggerFactory
	    .getLogger(SocketConnection.class);

    private final ExecutorService executor; // the executor that will send the
    // requests to the server
    private final SocketChannel connectedChannel; // the socket used for
    // communications
    // with the server
    private SocketRemoteServer server; // the server referenced by this
    // connection

    private final Object socketLock = new Object();

    // secs
    /*
     * Streams used to read and write from the socket
     */
    private final MessageOutputStream outputStream;
    private final MessageInputStream inputStream;
    

    /**
     * This lock is used to allow multiple threads to write and recevie messages
     * from this connection. But none can close the socket while someone is
     * reading.
     */
    // TODO: Double check wheter this is the right behaviour or not
    private final ReadWriteLock doNotCloseMeLock = new ReentrantReadWriteLock(
	    true);

    /**
     * Creates a <tt>SocketConnection</tt>.
     * <p>
     * This <tt>Connection</tt> will be bound to the address specified by the
     * passed {@link SocketRemoteServer} parameter
     * </p>
     * <p>
     * The created <tt>Connection</tt> will send requests and receive responses
     * by submitting those operations to the <code>executor</code> passed as
     * argument.
     * </p>
     * 
     * @param executor
     *            the {@link ExecutorService} that will execute the actual
     *            communication procedure
     * @param server
     *            a reference to the remote server this connection will be
     *            associated to
     * @param timeout
     *            a specified timeout for the underlying socket, in millis. A
     *            timeout of zero means no timeout
     * @throws IOException
     *             If an I/O error occurs.
     */
    protected SocketConnection(ExecutorService executor,
	    SocketRemoteServer server, int timeout, boolean useGzip) throws IOException {
	if (executor == null || server == null) {
	    log.error("Passed a null executor or server");
	    throw new IllegalArgumentException(
		    "Neither executor or server can be null");
	}

	this.executor = executor;
	this.server = server;

	InetSocketAddress socketAddr = server.getSocketAddress();

	connectedChannel = SocketChannel.open();

	if (!connectedChannel.connect(socketAddr)) {
	    throw new IOException(
		    "This exception should be thrown only if the channel is nonblocking");
	}

	connectedChannel.socket().setSoTimeout(timeout);

	outputStream = new MessageOutputStream(connectedChannel.socket()
		.getOutputStream(),useGzip);
	inputStream = new MessageInputStream(connectedChannel.socket()
		.getInputStream());

    }

    /**
     * Creates a <tt>SocketConnection</tt>.
     * <p>
     * This <tt>Connection</tt> will be bound to the address specified by the
     * passed {@link SocketRemoteServer} parameter
     * </p>
     * <p>
     * The created <tt>Connection</tt> will send requests and receive responses
     * by submitting those operations to the <code>executor</code> passed as
     * argument.
     * </p>
     * <p>
     * The connection will have a timeout value as specified in
     * {@link Connection#TIMEOUT_DEFAULT}
     * </p>
     * 
     * @param executor
     *            the {@link ExecutorService} that will execute the actual
     *            communication procedure
     * @param server
     *            a reference to the remote server this connection will be
     *            associated to
     * @throws IOException
     *             If an I/O error occurs.
     */
    protected SocketConnection(ExecutorService executor,
	    SocketRemoteServer server) throws IOException {
	this(executor, server, TIMEOUT_DEFAULT,true);
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.mentalsmash.tazio.net.cs.client.Connection#getRemoteServer()
     */
    @Override
    public RemoteServer getRemoteServer() {
	doNotCloseMeLock.readLock().lock();
	try {
	    return this.server;
	} finally {
	    doNotCloseMeLock.readLock().unlock();
	}
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.mentalsmash.tazio.net.cs.client.Connection#isValid()
     */
    @Override
    public boolean isValid() {
	doNotCloseMeLock.readLock().lock();
	try {
	    return server != null && connectedChannel.isConnected();
	} finally {
	    doNotCloseMeLock.readLock().unlock();
	}
    }

    /*
     * (non-Javadoc)
     * 
     * @seeorg.mentalsmash.tazio.net.cs.client.Connection#sendRequest(java.io.
     * Serializable)
     */
    @Override
    public Serializable sendRequest(Serializable request) throws IOException,
	    ConnectionStateExeption {

	Serializable response = null;

	doNotCloseMeLock.readLock().lock();
	try {
	    if (!isValid()) {
		String msg = "Invalid connection. Is the RemoteServer connected?";
		log.error(msg);
		throw new ConnectionStateExeption(msg);
	    }
	    synchronized (socketLock) {
		outputStream.writeMessage(request);
		response = inputStream.readMessage();
	    }
	} catch (ClassNotFoundException e) {
	    String msg = "Can't rebuild message object. Class not found";
	    log.error(msg, e);
	    throw new RuntimeCSSubsystemException(msg, e);
	} finally {
	    doNotCloseMeLock.readLock().unlock();
	}

	return response;
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.mentalsmash.tazio.net.cs.client.Connection#sendRequestAsync(java.
     * io.Serializable)
     */
    @Override
    public Future<Serializable> sendRequestAsync(final Serializable request)
	    throws ConnectionStateExeption {

	Future<Serializable> response;

	doNotCloseMeLock.readLock().lock();
	try {
	    if (!isValid()) {
		String msg = "Invalid connection. Is the RemoteServer connected?";
		log.error(msg);
		throw new ConnectionStateExeption(msg);
	    }

	    response = executor.submit(new Callable<Serializable>() {
		@Override
		public Serializable call() throws Exception {
		    Serializable response = null;

		    synchronized (socketLock) {
			outputStream.writeMessage(request);
			try {
			    response = inputStream.readMessage();
			} catch (ClassNotFoundException e) {
			    String msg = "Can't rebuild message object. Class not found";
			    log.error(msg, e);
			    throw new RuntimeCSSubsystemException(msg, e);
			}
		    }

		    return response;
		}
	    });
	} finally {
	    doNotCloseMeLock.readLock().unlock();
	}

	return response;
    }

    @Override
    public Future<RequestStatus> sendMessageAsync(final Serializable message)
	    throws ConnectionStateExeption {
	Future<RequestStatus> toReturn;

	doNotCloseMeLock.readLock().lock();

	try {
	    if (!isValid()) {
		String msg = "Invalid connection. Is the RemoteServer connected?";
		log.error(msg);
		throw new ConnectionStateExeption(msg);
	    }

	    toReturn = executor.submit(new Callable<RequestStatus>() {
		public RequestStatus call() throws Exception {
		    RequestStatus toReturn = null;

		    try {
			synchronized (socketLock) {
			    outputStream.writeMessage(message);
			}
		    } catch (Exception e) {
			toReturn = RequestStatus.EXCEPTION_OCCURRED; // nice but
			// useless
			throw e;
		    }

		    toReturn = RequestStatus.OK;

		    return toReturn;
		}
	    });
	} finally {
	    doNotCloseMeLock.readLock().unlock();
	}

	return toReturn;

    }

    @Override
    public void sendMessage(Serializable message) throws IOException,
	    ConnectionStateExeption {

	doNotCloseMeLock.readLock().lock();

	try {
	    if (!isValid()) {
		String msg = "Invalid connection. Is the RemoteServer connected?";
		log.error(msg);
		throw new ConnectionStateExeption(msg);
	    }
	    synchronized (socketLock) {
		outputStream.writeMessage(message);
	    }

	} finally {
	    doNotCloseMeLock.readLock().unlock();
	}

    }

    /*
     * (non-Javadoc)
     * 
     * @see org.mentalsmash.tazio.net.cs.client.Connection#close()
     */
    @Override
    public void close() {
	log.debug("Waiting for other threads to release the connection");
	doNotCloseMeLock.writeLock().lock(); // X-clusive
	log.debug("Closing the connection");

	try {
	    this.server.setConnection(null);
	    this.server = null;
	    try {
		inputStream.close();
		outputStream.close();
		connectedChannel.close();
	    } catch (IOException e) {
		log.debug("Error while closing connection.", e);
		// never mind, I'm closing...
	    }
	} finally {
	    doNotCloseMeLock.writeLock().unlock();
	}

    }

    /*
     * (non-Javadoc)
     * 
     * @see org.mentalsmash.tazio.net.cs.client.Connection#getTimeOut()
     */
    @Override
    public int getTimeOut() throws ConnectionStateExeption, IOException {
	if (!isValid()) {
	    String msg = "Invalid connection. Is the RemoteServer connected?";
	    log.error(msg);
	    throw new ConnectionStateExeption(msg);
	}
	doNotCloseMeLock.readLock().lock();
	try {
	    return this.connectedChannel.socket().getSoTimeout();
	} finally {
	    doNotCloseMeLock.readLock().unlock();
	}
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.mentalsmash.tazio.net.cs.client.Connection#setTimeOut(long)
     */
    @Override
    public void setTimeOut(int millis) throws ConnectionStateExeption,
	    IOException {

	if (!isValid()) {
	    String msg = "Invalid connection. Is the RemoteServer connected?";
	    log.error(msg);
	    throw new ConnectionStateExeption(msg);
	}

	if (millis < 0) {
	    log.warn("Someone tried to set a non positive timeout on {}", this);
	    throw new IllegalArgumentException("Timeout must be positive");
	}
	this.doNotCloseMeLock.writeLock().lock();
	try {
	    this.connectedChannel.socket().setSoTimeout(millis);
	} finally {
	    this.doNotCloseMeLock.writeLock().unlock();
	}

    }
    

}
